/**
 * 用户状态管理器
 * 管理用户身份信息和设备识别状态
 */
import { ref, computed } from 'vue'
import deviceFingerprint from '../utils/deviceFingerprint'

// 用户身份信息
const userIdentity = ref(null)

// 用户Token
const userToken = ref(null)

// 设备识别状态
const identificationStatus = ref('pending') // pending, loading, success, error

// 识别错误信息
const identificationError = ref(null)

/**
 * 用户状态管理
 */
export const useUserStore = () => {
  
  // 是否为新用户
  const isNewUser = computed(() => {
    return userIdentity.value?.isNewUser || false
  })

  // 访问次数
  const visitCount = computed(() => {
    return userIdentity.value?.visitCount || 0
  })

  // 预约次数
  const bookingCount = computed(() => {
    return userIdentity.value?.bookingCount || 0
  })

  // 是否已识别用户
  const isIdentified = computed(() => {
    return identificationStatus.value === 'success' && userToken.value
  })

  // 是否为临时用户（识别失败时的备选方案）
  const isTemporary = computed(() => {
    return userIdentity.value?.isTemporary || false
  })

  /**
   * 初始化用户识别
   */
  const initializeUser = async () => {
    try {
      identificationStatus.value = 'loading'
      identificationError.value = null
      
      console.log('🔍 开始初始化用户识别...')
      
      // 调用设备指纹识别
      const identity = await deviceFingerprint.initialize()
      
      if (identity) {
        userIdentity.value = identity
        userToken.value = identity.userToken
        identificationStatus.value = 'success'
        
        console.log('✅ 用户识别成功:', {
          userToken: identity.userToken,
          isNewUser: identity.isNewUser,
          visitCount: identity.visitCount,
          bookingCount: identity.bookingCount,
          isTemporary: identity.isTemporary
        })
        
        // 如果是新用户，显示欢迎信息
        if (identity.isNewUser && !identity.isTemporary) {
          console.log('🎉 欢迎新用户！')
        }
        
        return identity
      } else {
        throw new Error('用户识别返回空结果')
      }
    } catch (error) {
      console.error('❌ 用户识别失败:', error)
      identificationStatus.value = 'error'
      identificationError.value = error.message
      
      // 即使识别失败，也尝试获取临时身份
      const tempIdentity = deviceFingerprint.getUserIdentity()
      if (tempIdentity) {
        userIdentity.value = tempIdentity
        userToken.value = tempIdentity.userToken
      }
      
      return null
    }
  }

  /**
   * 更新用户访问信息
   */
  const updateVisitInfo = async () => {
    if (!userToken.value || userToken.value.startsWith('TEMP_')) {
      return
    }

    try {
      // 这里可以调用后端API更新访问信息
      // await request.post(`/anonymousUsers/updateVisit/${userToken.value}`)
      console.log('📊 更新用户访问信息:', userToken.value)
    } catch (error) {
      console.error('更新访问信息失败:', error)
    }
  }

  /**
   * 获取用户信息摘要
   */
  const getUserSummary = () => {
    if (!userIdentity.value) {
      return {
        status: '未识别',
        message: '正在识别用户身份...'
      }
    }

    const summary = {
      userToken: userToken.value,
      status: isTemporary.value ? '临时用户' : '已识别',
      isNewUser: isNewUser.value,
      visitCount: visitCount.value,
      bookingCount: bookingCount.value
    }

    if (isNewUser.value) {
      summary.message = '欢迎浏览华南师范大学美术学院VR展！'
    } else {
      summary.message = '欢迎回来！感谢您再次浏览华南师范大学美术学院VR展'
    }

    return summary
  }

  /**
   * 清除用户信息（用于测试）
   */
  const clearUserInfo = () => {
    userIdentity.value = null
    userToken.value = null
    identificationStatus.value = 'pending'
    identificationError.value = null
    deviceFingerprint.clearUserInfo()
    console.log('🧹 用户信息已清除')
  }

  /**
   * 重新识别用户
   */
  const reidentifyUser = async () => {
    console.log('🔄 重新识别用户...')
    clearUserInfo()
    return await initializeUser()
  }

  return {
    // 状态
    userIdentity,
    userToken,
    identificationStatus,
    identificationError,
    
    // 计算属性
    isNewUser,
    visitCount,
    bookingCount,
    isIdentified,
    isTemporary,
    
    // 方法
    initializeUser,
    updateVisitInfo,
    getUserSummary,
    clearUserInfo,
    reidentifyUser
  }
}

// 导出单例实例
let userStoreInstance = null

export const getUserStore = () => {
  if (!userStoreInstance) {
    userStoreInstance = useUserStore()
  }
  return userStoreInstance
} 